package handler

import (
	model "funlog-gserver/model/db"
	"funlog-gserver/stored/db"
	"funlog-gserver/utils"
	"net/http"
	"strconv"

	"github.com/gin-gonic/gin"
)

//Response 响应结构体
type Response struct {
	Code    int         `json:"code"`
	Message string      `json:"message"`
	Data    interface{} `json:"data"`
}

const (
	SUCCESS      = 0
	SYATEM_ERROR = iota + 9
	DB_INSERT_ERROR
	DB_QUERY_ERROR
	DB_UPDATE_ERROR
	DB_DELETE_ERROR
	OPERATION_FAILED       //操作失败
	QUERY_PARAMS_ERROR     //参数错误
	CAPTCHA_ERROR          //验证码错误
	INADEQUATE_PERMISSIONS //权限不足
	INVALID_INFORMATION    //无效信息
	RDB_QUERY_ERROR        //redis查询错误
	RDB_INSER_ERROR        //redis插入错误
	ES_QUERY_ERROR         //es查询错误了
)

//SendResponse 发送一个json 信息到客户端公共方法
func SendResponse(c *gin.Context, code int, message string, data interface{}) {
	c.JSON(http.StatusOK, Response{
		Code:    code,
		Message: message,
		Data:    data,
	})
}

//GetUser 获取当前登陆的用户信息
func GetUser(c *gin.Context) (uid uint, user map[string]interface{}) {
	userIn, exists := c.Get("user")
	if !exists {
		return
	}
	//用户信息map
	user = userIn.(map[string]interface{})
	tuid, _ := strconv.ParseUint(utils.Strval(user["id"]), 10, 32)
	//用户id
	uid = uint(tuid)
	var teamIds []string
	teamRelation := []model.TeamRelation{}
	//查询用户所在团队别
	result := db.DB.Where("uid=? and status =1", uid).Find(&teamRelation)
	if result.Error == nil {
		for i := 0; i < len(teamRelation); i++ {
			teamIds = append(teamIds, utils.Strval(teamRelation[i].TID))
		}
		user["teamIds"] = teamIds
	}

	return
}
